package com.gitee.feizns.web.boot.ex;

import com.gitee.feizns.web.ex.GlobalRestfulExceptionAdvice;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * @author feizns
 * @since 2019/6/13
 */
@Configuration
@EnableConfigurationProperties(GlobalExceptionProperties.class)
public class GlobalExceptionAutoConfiguration implements ApplicationContextAware {

    @Autowired
    private GlobalExceptionProperties properties;

    @Bean
    @ConditionalOnMissingBean(GlobalRestfulExceptionAdvice.class)
    public GlobalRestfulExceptionAdvice globalRestfulExceptionAdvice() {
        return new GlobalRestfulExceptionAdvice(properties);
    }

    @Override
    public void setApplicationContext(ApplicationContext app) throws BeansException {
        Map<String, GlobalExceptionConfigurer> beans = app.getBeansOfType(GlobalExceptionConfigurer.class);
        if ( beans != null ) {
            for (GlobalExceptionConfigurer configurer : beans.values()) {
                configurer.extendsErrorHandlerMapping(properties.getExceptionHandlerMap());
                configurer.registryErrorMapping(properties.getErrMap());
            }
        }
    }

}
